//
//  BCWalletController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/15.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCWalletController.h"

//余额视图
#import "BCWalleteBalanceView.h"


//充币controller
#import "BCRechargeCoinController.h"
//提币
#import "BCPutCoinController.h"
//兑换
#import "BCWalletExchangeController.h"
//资金明细
#import "BCWalletDetailController.h"
#import "BCWalletDetailPagerController.h"

//选择单位 USD/CNY
#import "BCMonetaryUnitView.h"

//cell以及header
#import "BCWalletSectionHeaderView.h"
#import "BCWalletCell.h"

//按钮视图
#import "BCWalletBottomView.h"

//refresh
#import "BCRefreshNormalHeader.h"


//request
#import "BCUserWalletRequest.h"

@interface BCWalletController () <BCWalleteBalanceViewDelegate,BCMonetaryUnitViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *walletTable;

/**
 *stretch拉伸视图 contentOffset.y <0 时拉伸
 */
@property (nonatomic, strong) UIView *stretchView;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;

/**
 *余额视图
 */
@property (nonatomic, strong) BCWalleteBalanceView *balanceView;

/**
 *BCWalletBottomView
 */
@property (nonatomic, strong) BCWalletBottomView *bottomView;

/**
 *兑换按钮
 */
@property (nonatomic, strong) QMUIButton *exchangeButton;


/**
 *weak 一下 方便判断是否存在
 */
@property (nonatomic, strong) BCMonetaryUnitView *monetaryUnitView;


#pragma mark -
/**
 *BCUserWalletData
 */
@property (nonatomic, strong) BCUserWalletData *walletData;

/**
 *当前显示的货币单位 USD、CNY
 */
@property (nonatomic, copy) NSString *monetaryUnit;

@end

@implementation BCWalletController

- (BCWalleteBalanceView *)balanceView {
    if (!_balanceView) {
        _balanceView = [BCWalleteBalanceView new];
        _balanceView.delegate = self;
        _balanceView.backgroundColor = self.customNaviBar.backgroundColor;
        _balanceView.frame = CGRectMake(0, 0, self.view.frame.size.width, [BCWalleteBalanceView defaultHeight]);
    }
    return _balanceView;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
        _refreshHeader.animateCircleClolor = [UIColor darkSubMainColor];
    }
    return _refreshHeader;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.customNaviBar.backgroundColor = [UIColor darkMainColor];
//    self.title = BCLocalizedKey(@"uc_my_wallet");
    //
    [self setupSubviews];
    //
    BCUserWalletData *walletData = [BCUserManager sharedUser].walletData;
    if (walletData) {
        _monetaryUnit = walletData.monetaryUnit;
        [self handleWalletResponseData:walletData];
    }else {
        [self.refreshHeader beginRefreshing];
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //
    [self refreshHeaderAction];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self dismissMonetaryUnitView:false];
}

- (void)setupSubviews {
//    [self.customNaviBar.rightButton setTitle:BCLocalizedKey(@"wallet_money_detail") forState:UIControlStateNormal];
    //
    self.bottomView = [BCWalletBottomView new];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo([BCWalletBottomView defaultHeight]);
    }];
    [self.bottomView.leftButton addTarget:self action:@selector(rechargeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView.rightButton addTarget:self action:@selector(putButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    self.bottomView.alpha = 0;
    //
    self.walletTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.walletTable.dataSource = self;
    self.walletTable.delegate = self;
    self.walletTable.separatorStyle = UITableViewCellSelectionStyleNone;
    self.walletTable.showsVerticalScrollIndicator = false;
    [self.view addSubview:self.walletTable];
    [self.walletTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
    }];
    //
    self.stretchView = [UIView new];
    self.stretchView.backgroundColor = self.customNaviBar.backgroundColor;
    [self.walletTable addSubview:self.stretchView];
    [self.stretchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.walletTable);
        make.bottom.mas_equalTo(self.walletTable.mas_top);
        make.width.mas_equalTo(self.walletTable);
        make.height.mas_equalTo(1000);
    }];
//    [self.walletTable setTableHeaderView:self.balanceView];
    //
    [self.walletTable registerClass:BCWalletCell.class forCellReuseIdentifier:NSStringFromClass(BCWalletCell.class)];
    [self.walletTable registerClass:BCWalletSectionHeaderView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(BCWalletSectionHeaderView.class)];
    //
    [self.walletTable setMj_header:self.refreshHeader];
    [self.walletTable bringSubviewToFront:self.refreshHeader];
    //兑换按钮
    self.exchangeButton = [QMUIButton new];
    [self.exchangeButton setImage:LOAD_IMAGE(@"wallet_exchange_btn") forState:UIControlStateNormal];
    [self.view addSubview:self.exchangeButton];
    [self.exchangeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view).offset(-25.0);
        make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-30.0*WidthScale);
    }];
    [self.exchangeButton addTarget:self action:@selector(exchangeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    self.exchangeButton.alpha = 0;
    
    //
    [self.view layoutIfNeeded];
}

//设置货币单位
- (void)setMonetaryUnit:(NSString *)monetaryUnit {
    _monetaryUnit = monetaryUnit;
    if (self.walletData) {//g如果有数据重新加载
        //先判断是否含有此单位
        NSArray *allKeys = self.walletData.currency.allKeys;
        if (allKeys.count) {
            if (![allKeys containsObject:monetaryUnit]) {
                _monetaryUnit = allKeys[0];
            }
            //
            self.walletData.monetaryUnit = _monetaryUnit;
            [self reloadTableData:self.walletData];
        }
        //
        //更新到当前登录用户管理中
        [BCUserManager sharedUser].walletData = _walletData;
    }
}


- (void)didClickedNaviRightButton {
    [self toWalletDetailAction];
}

#pragma mark - refreshHeaderAction
- (void)refreshHeaderAction {
    [self requestWalletData];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.walletData) {
        if (section==0) {
            return 1;
        }
        return self.walletData.balance.count;
    }else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCWalletCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCWalletCell.class)];
    if (indexPath.section==0) {
        cell.isTitle = true;
        cell.walletData = self.walletData;
    }else {
        cell.isTitle = false;
        [cell setBalance:self.walletData.balance[indexPath.row] monetaryUnit:self.walletData.monetaryUnit];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [BCWalletCell defaultHeight];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self dismissMonetaryUnitView:true];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - BCWalleteBalanceViewDelegate
//选择金额单位按钮点击去选择单位
- (void)walletBalnaceView:(BCWalleteBalanceView *)balanceView didClickedBalanceButtonWithArrowConvertFrame:(CGRect)arrowConverFrame {
    if (self.monetaryUnitView) {
        [self dismissMonetaryUnitView:true];
        return;
    }
    //得到arrowConverFrame转换到walletScroll的frmae
    CGRect convertFrame = [balanceView convertRect:arrowConverFrame toView:self.walletTable];
    //
    NSArray *source = self.walletData.currency.allKeys;
    CGSize monetaryUnitSize = [BCMonetaryUnitView monetaryUnitSize:source];
    //计算是left显示或者right显示
    BOOL left = true;
    CGFloat leftLastWidth = self.walletTable.frame.size.width-convertFrame.origin.x-convertFrame.size.width-10.0;
    if (monetaryUnitSize.width>leftLastWidth) {
        left = false;
    }
    //当前偏移亮 向上
    CGFloat offset = 6.0;
    //计算frame
    CGRect frame = CGRectMake(CGRectGetMaxX(convertFrame), CGRectGetMinY(convertFrame)-offset, monetaryUnitSize.width, monetaryUnitSize.height);
    if (!left) {
        frame = CGRectMake(CGRectGetMinX(convertFrame)-monetaryUnitSize.width-5.0, CGRectGetMinY(convertFrame)-offset, monetaryUnitSize.width, monetaryUnitSize.height);
    }
    //计算anchorPoint
    CGPoint anchorPoint = CGPointMake(0, 0);
    CGFloat anchorPointY = MAX(0, (CGRectGetMidY(convertFrame)-CGRectGetMinY(frame))/CGRectGetHeight(frame));
    if (left) {
        anchorPoint = CGPointMake(0, anchorPointY);
    }else {
        anchorPoint = CGPointMake(1, anchorPointY);
    }
    //
    BCMonetaryUnitView *monetaryUnitView = [[BCMonetaryUnitView alloc] initWithArrowLeft:left];
    monetaryUnitView.delegate = self;
    monetaryUnitView.layer.anchorPoint = anchorPoint;
    [self.walletTable addSubview:monetaryUnitView];
    //
    [monetaryUnitView setArrowCenterY:CGRectGetMidY(convertFrame)-CGRectGetMinY(frame) maxWidth:frame.size.width];
    //
    [monetaryUnitView setMonetaryUnitViewSource:source];
    //
    monetaryUnitView.frame = frame;
    //animate
    monetaryUnitView.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:0.3 animations:^{
        monetaryUnitView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
    }];
    self.monetaryUnitView = monetaryUnitView;
}
#pragma mark - monetaryUnitView相关
//BCMonetaryUnitViewDelegate
- (void)monetaryUnitViewDidSelectMonetaryUnit:(NSString *)monetaryUnit {
    [self dismissMonetaryUnitView:true];
    //
    self.monetaryUnit = monetaryUnit;
}
//移除monetaryUnitView
- (void)dismissMonetaryUnitView:(BOOL)animate {
    if (self.monetaryUnitView) {
        if (animate) {
            [UIView animateWithDuration:0.3 animations:^{
                self.monetaryUnitView.transform = CGAffineTransformMakeScale(0.01, 0.01);
            } completion:^(BOOL finished) {
                [self.monetaryUnitView removeFromSuperview];
                self.monetaryUnitView = nil;
            }];
        }else {
            [self.monetaryUnitView removeFromSuperview];
            self.monetaryUnitView = nil;
        }
    }
}


#pragma mark - request
- (void)requestWalletData {
    BCUserWalletRequest *request = [BCUserWalletRequest new];
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.refreshHeader endRefreshing];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserWalletResponse *resp = result;
        [wself handleWalletResponseData:resp.data];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}
- (void)handleWalletResponseData:(BCUserWalletData *)walletData {
    if (walletData) {
        self.walletData = walletData;
        //
        self.title = walletData.flow.title;
        [self.customNaviBar.rightButton setTitle:walletData.flow.right forState:UIControlStateNormal];
        //
        self.monetaryUnit = self.monetaryUnit.length==0?walletData.default_curr:self.monetaryUnit;
        //
        self.bottomView.alpha = 1;
        [self.bottomView.leftButton.displayButton setTitle:walletData.flow.recharge forState:UIControlStateNormal];
        [self.bottomView.rightButton.displayButton setTitle:walletData.flow.cash forState:UIControlStateNormal];
        //
        self.exchangeButton.alpha = 1;
    }
}
//该方法在设置货币单位后使用 请确保已经设置了单位
- (void)reloadTableData:(BCUserWalletData *)walletData {
    if (walletData) {
        [self.walletTable setTableHeaderView:self.balanceView];
        self.balanceView.walletData = walletData;
    }else {
        self.walletTable.tableHeaderView = nil;
    }
    [self.walletTable reloadData];
}



#pragma mark - rechargeButtonDidClickedAction
- (void)rechargeButtonDidClickedAction {
    [self toRechargeCoinAction];
}
#pragma mark - putButtonDidClickedAction
- (void)putButtonDidClickedAction {
    [self toPutCoinAction];
}
#pragma mark - exchangeButtonDidClickedAction
- (void)exchangeButtonDidClickedAction {
    [self toExchangeAction];
}

/**
 去充币
 */
- (void)toRechargeCoinAction {
    BCRechargeCoinController *recharge = [BCRechargeCoinController new];
    [self.navigationController pushViewController:recharge animated:true];
}
/**
 去提币
 */
- (void)toPutCoinAction {
    BCPutCoinController *put = [BCPutCoinController new];
    [self.navigationController pushViewController:put animated:true];
}
/**
 去资金明细
 */
- (void)toWalletDetailAction {
//    BCWalletDetailController *detail = [BCWalletDetailController new];
//    [self.navigationController pushViewController:detail animated:true];
    
    BCWalletDetailPagerController *detailPager = [BCWalletDetailPagerController new];
    detailPager.title = self.walletData.flow.right;
    detailPager.menus = self.walletData.menus;
    [self.navigationController pushViewController:detailPager animated:true];
}
/**
 去兑换
 */
- (void)toExchangeAction {
    BCWalletExchangeController *exchange = [BCWalletExchangeController new];
    [self.navigationController pushViewController:exchange animated:true];
}

@end
